package com.easonji.core.shiro.check;

import com.easonji.common.util.CollectionUtils;
import com.easonji.common.util.HttpUtils;
import com.easonji.common.util.SpringContextHolder;
import com.easonji.common.util.StringUtils;
import com.easonji.core.exception.BizException;
import com.easonji.core.listener.ConfigListener;
import com.easonji.core.shiro.ShiroUser;
import com.easonji.core.shiro.util.ShiroUtils;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: PermissionCheckFactoryImpl
 * @Description: 权限自定义检查
 * @Author: LiuJun
 * @date: 2018/07/09 11:28
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
@Service
@DependsOn("springContextHolder")
@Transactional(readOnly = true, rollbackFor = BizException.class)
public class PermissionCheckFactoryImpl implements PermissionCheckFactory {

    public static PermissionCheckFactory me() {
        return SpringContextHolder.getBean(PermissionCheckFactory.class);
    }

    @Override
    public Boolean check(Object[] permissions) {
        ShiroUser user = ShiroUtils.getUser();
        if (null == user) {
            return false;
        }
        String join = CollectionUtils.join(permissions, ",");
        if (ShiroUtils.hasAnyRoles(join)) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean checkAll() {
        ShiroUser user = ShiroUtils.getUser();
        if (null == user) {
            return false;
        }
        HttpServletRequest request = HttpUtils.getRequest();
        String url = request.getRequestURI().replaceFirst(ConfigListener.getConf().get("contextPath"), "");
        String param = url.substring(url.lastIndexOf("/") + 1);
        if (StringUtils.isNum(param)) {
            url = url.substring(0, url.lastIndexOf("/"));
        }
        // 验证权限
        if (ShiroUtils.hasPermission(url)) {
            return true;
        }
        return false;
    }
}
